package com.ustadzmenjawab.twitter;

import java.sql.Timestamp;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.ustadzmenjawab.conf.Configuration;
import com.ustadzmenjawab.db.DBAccess;
import com.ustadzmenjawab.log.OutputWriter;

import twitter4j.HashtagEntity;
import twitter4j.MediaEntity;
import twitter4j.RateLimitStatus;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
import twitter4j.UserMentionEntity;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterStatusListener implements StatusListener {

	private OutputWriter log ; 
	private DBAccess db;
	private Twitter restAPI;
	private ConcurrentLinkedQueue<Status> statusBuffer;
	public TwitterStatusListener(ConcurrentLinkedQueue<Status> statusBuffer){
		log = new OutputWriter();
		db = new DBAccess();
		this.statusBuffer = statusBuffer;
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		.setIncludeRTsEnabled(true)
		.setIncludeEntitiesEnabled(true)
		.setOAuthConsumerKey(Configuration.getProperty("REST_OAUTH_CONSUMER_KEY"))
		.setOAuthConsumerSecret(Configuration.getProperty("REST_OAUTH_CONSUMER_SECRET"))
		.setOAuthAccessToken(Configuration.getProperty("REST_OAUTH_ACCESS_TOKEN"))
		.setOAuthAccessTokenSecret(Configuration.getProperty("REST_OAUTH_ACCESS_TOKEN_SECRET"));
		twitter4j.conf.Configuration twconf = cb.build();
		restAPI = new TwitterFactory(twconf).getInstance();
		try {
			System.out.println("Rest API hourly rate limit : " + restAPI.getRateLimitStatus().getHourlyLimit());
		} catch (TwitterException e) {

			e.printStackTrace();
		}
	}
	@Override
	public void onException(Exception ex) {
		ex.printStackTrace();

	}

	@Override
	public void onDeletionNotice(StatusDeletionNotice delNotice) {

		long statusid = delNotice.getStatusId();
		db.deleteStatus(statusid);
		log.println("Delete statusid " + statusid );
	}

	@Override
	public void onScrubGeo(long arg0, long arg1) {

	}

	@Override
	public void onStatus(final Status status) {
		statusBuffer.add(status);
		log.println("New tweet by " + status.getUser().getId()+" , "+  status.getUser().getScreenName());
		
		
	}

	@Override
	public void onTrackLimitationNotice(int arg0) {

	}

	
	public void updateUntruncatedText(final Status status){
		new Thread(new Runnable(){

			@Override
			public void run() {
				try {
					System.out.println("Get untruncated text for status " + status.getId());
					while(true){
						RateLimitStatus rateLimit = restAPI.getRateLimitStatus();
						if(rateLimit.getRemainingHits() > 0){
							Status retweetedStatus = restAPI.retweetStatus(status.getId());
							if(retweetedStatus != null && retweetedStatus.getRetweetedStatus() != null){
								retweetedStatus = retweetedStatus.getRetweetedStatus();
								
								db.updatePublicTweet(retweetedStatus);
								
							}
							break;
							
						}else{
							System.out.println("Hit limit exceded, sleep for "+rateLimit.getSecondsUntilReset() + " seconds.");
							Thread.sleep(rateLimit.getSecondsUntilReset() *1000);
						}
					}
					
				} catch (TwitterException e) {

					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}).start();
	}

	
	
	
}
